<template>
  <qx-table ref="DictDataTable" :option="formOption" :remoteData="remoteData">
    <template v-slot:menuLeft="{ selected }">
      <q-btn v-if="btnShow" v-auth="['cfgDict:save']" color="primary" icon="add" unelevated @click="handleCreate">
        {{ $t('Add') }}
      </q-btn>
      <q-btn v-auth="['cfgDict:update']" :disable="isDisable(selected)" icon="mdi-square-edit-outline" outline
             text-color="primary" @click="handleUpdate(selected[0])">
        {{ $t('Edit') }}
      </q-btn>
      <q-btn v-if="btnShow" v-auth="['cfgDict:delete']" :disable="isDisable(selected)" icon="delete" outline
             text-color="primary" @click="handleDelete(selected[0])">
        {{ $t('Del') }}
      </q-btn>
    </template>
    <template v-slot:dictTypeCode="{ row }">
      <q-link @click="handleUpdate(row)">{{ row.dictTypeCode }}</q-link>
    </template>
  </qx-table>

  <q-modal v-model="modalVisible" :header="formInfo.id ? $t('Edit') : $t('Add')" :width="500" btnAlign="center"
           position="right" @beforeClose="beforeClose" @confirm="submitForm">
    <qx-form ref="DictDataCfg" v-model="formInfo" :option="formOption"></qx-form>
  </q-modal>
</template>

<script setup>
import { deleteAPI, postAPI, putAPI } from 'src/api'
import { i18n, toI18nName } from 'boot/i18n'
import { isAuth } from 'src/directives/v-auth.js'
import { yesOrNo } from 'src/enum'
import { setDictData } from 'src/enum/ajaxRemoteData.js'
import { createDialog, deepClone } from 'src/utils/utils'
import { computed, onMounted, ref, watch } from 'vue'

const props = defineProps({ rowInfo: Object })

const formInfo = ref({})
const searchForm = ref({})
const DictDataCfg = ref(null)
const DictDataTable = ref(null)
const modalVisible = ref(false)
const remoteData = ref({ dicUrl: '/config/api/cfgDictData/list' })

const btnShow = computed(() => (props.rowInfo || {}).sysInner !== '1')
const isDisable = computed(() => selected => !selected || selected.length !== 1)
const formOption = computed(() => {
  return {
    labelWidth: 100, searchLabelWidth: 70, selection: 'single', menuBtn: false, span: 22,
    column: [{
      label: `${i18n.t('SystemCore.DictType')}`, field: 'dictTypeCode', required: true, readonly: true, minWidth: 80,
      slot: isAuth(['cfgDict:update'])
    }, {
      label: `${i18n.t('SystemCore.DictNameENUS')}`, field: 'dictNameEnUs', hide: true, minWidth: 80
    }, {
      label: `${i18n.t('SystemCore.DictName')}`, field: 'dictNameZhCn', required: true,
      format: (_, row) => row[toI18nName('dictNameZhCn')], minWidth: 80
    }, {
      label: `${i18n.t('SystemCore.DictKey')}`, field: 'dictKey', required: true, readonly: !!formInfo.value.id,
      minWidth: 80
    }, {
      label: `${i18n.t('SystemCore.DictValue')}`, field: 'dictValue', required: true, minWidth: 80
    }, {
      label: `${i18n.t('Sorting')}`, field: 'sortId', type: 'number', min: 0, decimals: 0, required: true,
      minWidth: 60, hide: true
    }, {
      label: `${i18n.t('BuiltIn')}`, field: 'sysInner', search: false, display: false, options: yesOrNo.value,
      align: 'center', useTag: true, minWidth: 80
    }, {
      label: `${i18n.t('CreationTime')}`, field: 'createdTime', display: false, minWidth: 80
    }, {
      label: `${i18n.t('Remarks')}`, field: 'remark', type: 'textarea', search: false, minWidth: 120, maxlength: 200
    }]
  }
})

const handleCreate = () => {
  formInfo.value = { dictTypeCode: props.rowInfo.dictTypeCode }
  modalVisible.value = true
}
const handleUpdate = row => {
  formInfo.value = deepClone(row)
  modalVisible.value = true
}
const formatSearchForm = () => {
  const params = { ...searchForm.value }
  params.orderByItems = [{ orderType: 'ASC', property: 'sortId' }]
  params.andDynamicQueryItems =
    [{ criterion: 'andEqualTo', property: 'dictTypeCode', value: props.rowInfo.dictTypeCode }]
  return params
}
onMounted(() => startSearch())
watch(() => props.rowInfo?.id, () => startSearch('clearRows'))

const clearSelection = () => DictDataTable.value && DictDataTable.value.clearSelection()
const handleDelete = row => {
  createDialog({ msg: `${i18n.t('DelTips')}` }, () => {
    deleteAPI(`/config/api/cfgDictData/${row.id}`, {}, () => {
      setDictData(row.dictTypeCode, [])
      startSearch()
    })
  }, () => {})
}
const beforeClose = () => {
  if (DictDataCfg.value) DictDataCfg.value.onReset()
  modalVisible.value = false
}
const startSearch = (action, done) => {
  remoteData.value.params = formatSearchForm()
  if (action === 'clearRows') remoteData.value.clearRows = true
  remoteData.value.clearSelected = true
  if (done) done()
}
const submitForm = mDone => {
  DictDataCfg.value.validate((form, done) => {
    const API = form.id ? putAPI : postAPI
    API('/config/api/cfgDictData', form, () => {
      setDictData(form.dictTypeCode, [])
      startSearch()
      done()
      mDone && mDone()
    }, () => {
      done()
      mDone && mDone(false)
    })
  }, () => {
    mDone && mDone(false)
  })
}
defineExpose({ clearSelection })
</script>